 import React,{ Component} from 'react';
 import { Button } from 'antd';
 import { FolderOpenTwoTone } from '@ant-design/icons';
 import { Terminal } from 'xterm';
 import { FitAddon } from 'xterm-addon-fit';
 import FileManager from './FileManager';
//  import { http, X_TOKEN } from 'libs';
//  import { service } from '../../utils/request';
 import { getSShData } from "../../api/raycloud";
 import 'xterm/css/xterm.css';
 import './index.scss';
 import io from 'socket.io-client';
 
 
 class WebSSH extends Component {
   constructor(props) {
     super(props);
     this.id = props.match.params.id;
     this.socket = null;
     this.term = new Terminal();
     this.container = null;
     this.input = null;
     this.state = {
       visible: false,
       uploading: false,
       managerDisabled: true,
       host: {},
       percent: 0
     }
   }
   
   componentDidMount() {
      // 获取host信息
      this._fetch();
      // canvas背景全屏
      const fitPlugin = new FitAddon();
      this.term.loadAddon(fitPlugin);
      const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
      const namespace = '/ws/ssh';
      const url = `${protocol}//127.0.0.1:5000${namespace}`;
      this.socket = io(url);
      // 发送到服务器的通信内容
      this.socket.on('connect', (msg) => {
          console.log(msg);
          console.log('websocket connected')
          this.term.open(this.container);      // 将term挂载到dom节点上      
          this.term.focus();     // 终端添加focus事件的监听, dispose函数可以取消监听
          fitPlugin.fit();
      });
      // 接收服务端消息
      this.socket.on('message', e => { 
          console.log(e)
          this._read_as_text(e.data)
      });
      // 关闭连接回调
      this.socket.on('disconnect', (msg) => { 
          console.log(msg)
          if (msg.code === 3333) {
            window.location.href = "about:blank";
            window.close()
          } else {
            setTimeout(() => this.term.write('\r\nConnection is closed.\r\n'), 200)
          }
      });
      // 连接error
      this.socket.onerror = (e) => {
          console.log(e)
      };
      this.term.onData(data => this.socket.send(JSON.stringify({data})));
      this.term.onResize(({cols, rows}) => {
          this.socket.send(JSON.stringify({resize: [cols, rows]}))
      });
      window.onresize = () => fitPlugin.fit()
   }
 
   _read_as_text = (data) => {
      console.log(data)
      const reader = new window.FileReader();
      reader.onload = () => this.term.write(reader.result);
      console.log(reader)
      reader.readAsText(data, 'utf-8')
   };
 
   handleShow = () => {
      this.setState({visible: !this.state.visible})
   };
 
   _fetch = () => {
      //  http.get(`/api/host/?id=${this.id}`)
      const requestData = {
        id: this.id
      }
      getSShData(requestData).then(res => {
          const resp = res.data.data.items[0];
          document.title = resp.name;
          console.log(resp)
          this.setState({host: resp, managerDisabled: false})
        })
   };
 
   render() {
      const {host, visible, managerDisabled} = this.state;
      return (
          <div className="container">
            <div className="header">
              <div>{host.name} | {host.username}@{host.hostname}:{host.port}</div>
                <Button 
                    disabled={managerDisabled} 
                    type="primary" 
                    icon={<FolderOpenTwoTone />}
                    onClick={this.handleShow}>文件管理器
                </Button>
            </div>
            <div className="terminal">
              <div ref={ref => this.container = ref}/>
            </div>
            <FileManager id={this.id} visible={visible} onClose={this.handleShow}/>
          </div>
        )
    }
 }
 
 export default WebSSH